package com.yjf.ljr.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class SecurityUtil {
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	//定义加密算法，有DES、DESede(即3DES)、Blowfish
    private static final String Algorithm = "DESede";    
    private static final String PASSWORD_CRYPT_KEY = "f5b41db378de4cf3a669c55a9f3c8487";//密钥
	
	private static String MD5Encode(String fact, String salt) {
		String result = null;
		if (null == salt){
			salt = "";
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			String source = String.format("%s{%s}", fact, salt);
			// 加密后的字符串
			result = byteArrayToHexString(md.digest(source.getBytes("utf-8")));
		}
		catch (Exception e) {
		}
		return result;
	}
	
	public static String MD5Encode(String fact) {
		String result = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			String source = fact;
			// 加密后的字符串
			result = byteArrayToHexString(md.digest(source.getBytes("utf-8")));
			result = result.toUpperCase();
		}
		catch (Exception e) {
		}
		return result;
	}

	/**
	 * 转换字节数组为16进制字串
	 */
	private static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0){
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}
	
	/**
     * 加密方法
     * @param src 源数据的字节数组
     * @return 
     */
    public static byte[] encryptMode(byte[] src) {
        try {
             SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);    //生成密钥
             Cipher c1 = Cipher.getInstance(Algorithm);    //实例化负责加密/解密的Cipher工具类
             c1.init(Cipher.ENCRYPT_MODE, deskey);    //初始化为加密模式
             return c1.doFinal(src);
         } 
         catch (Exception e) {
         }
         return null;
     }
    
    
    /**
     * 解密函数
     * @param src 密文的字节数组
     * @return
     */
    public static byte[] decryptMode(byte[] src) {      
        try {
            SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.DECRYPT_MODE, deskey);    //初始化为解密模式
            return c1.doFinal(src);
        } 
        catch (Exception e) {
        }
        return null;
     }
    
    
    /*
     * 根据字符串生成密钥字节数组 
     * @param keyStr 密钥字符串
     * @return 
     * @throws UnsupportedEncodingException
     */
    public static byte[] build3DesKey(String keyStr){
        byte[] key = new byte[24];    //声明一个24位的字节数组，默认里面都是0
		try {
			 byte[] temp = keyStr.getBytes("UTF-8");
		    //将字符串转成字节数组
	        /*
	         * 执行数组拷贝
	         * System.arraycopy(源数组，从源数组哪里开始拷贝，目标数组，拷贝多少位)
	         */
	        if(key.length > temp.length){
	            //如果temp不够24位，则拷贝temp数组整个长度的内容到key数组中
	            System.arraycopy(temp, 0, key, 0, temp.length);
	        }else{
	            //如果temp大于24位，则拷贝temp数组24个长度的内容到key数组中
	            System.arraycopy(temp, 0, key, 0, key.length);
	        }
		}
		catch (UnsupportedEncodingException e) {
		}   
        return key;
    } 
	
	public static void main(String[] args){
		
		System.out.println(MD5Encode("20140220101328","htq"));
		 //String msg = "3DES加密解密案例";
		 String msg = "app.load";
	     System.out.println("【加密前】：" + msg);
	         
         //3des加密
         byte[] secretArr = encryptMode(msg.getBytes());    
         System.out.println("【加密后】：" + new String(secretArr));
         
         //3des解密
         byte[] myMsgArr = decryptMode(secretArr);  
         System.out.println("【解密后】：" + new String(myMsgArr));
	}
}
